package cn.dengta.webapp.trade.service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

import cn.dengta.webapp.base.entity.BizEntity;
import cn.dengta.webapp.base.service.BaseServiceImpl;
import cn.dengta.webapp.trade.dao.UserVipEquityDao;
import cn.dengta.webapp.trade.entity.UserVipEquity;
import cn.dengta.webapp.user.model.Gender;
import cn.dengta.webapp.user.model.UserVipRule;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import static cn.dengta.webapp.trade.entity.UserVipEquity.GENDER;
import static cn.dengta.webapp.trade.entity.UserVipEquity.ID;

/**
 * 个人VIP 权益配置 服务实现类
 *
 * @author zw
 * @since 2022-08-03
 */
@Service
public class UserVipEquityService extends BaseServiceImpl<UserVipEquity, UserVipEquityDao, Long> {

	static Map<Long, UserVipRule> cache = new ConcurrentHashMap<>(8);

	final Function<Long, UserVipRule> mappingFunction = id -> {
		UserVipEquity equity = get(id);
		return equity == null ? null : equity.getUserVipConfig();
	};

	public UserVipRule getCached(Long configId) {
		return cache.computeIfAbsent(configId, mappingFunction);
	}

	public UserVipEquity getByStatus(Gender gender) {
		if (gender == null) {
			return null;
		}
		QueryWrapper<UserVipEquity> wrapper = new QueryWrapper<UserVipEquity>()
				.eq(GENDER, gender.getValue())
				.eq(BizEntity.STATUS, 1)
				.orderByDesc(ID)
				.last("LIMIT 1");
		return baseDao.selectOne(wrapper);
	}

}
